# coding:utf-8
import argparse
import datetime
import os
import subprocess
import sys
import paramiko
import pysequoiadb
from pysequoiadb import client
from pysequoiadb.error import SDBBaseError
from pysequoiadb.error import SDBEndOfCursor
flags = argparse.ArgumentParser()
flags.add_argument("--sdb_ip",type=str,help='ip of sdb')
args = flags.parse_args()
sdb_ip = args.sdb_ip
sdb_port = "11810"
sdb_user = "peter"
sdb_password = "Foxconn99."
collection_name = "port"
serverinfo_collection_name = "serverinfo"


def check_ping_status(ip):
    res = subprocess.Popen("ping -c 2 " + ip + " | grep received", shell=True, stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    out = res.stdout.read()
    print(out)
    out = out.split(' ')[3]
    try:
        out = int(out)
        if out > 0:
            return True
        else:
            return False
    except:
        print('occur error')
        return False
def check_ip_port(ip,port):
    try:
        res = subprocess.Popen("sh /data/script/test_server_port.sh " + ip + " " + port,shell=True, stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
        out = res.stdout.read()
        out = out.split(' ')[-1].strip('\n')

        if out == 'open':
            status = 1
        else:
            status = 0
        return status
    except Exception as e:
        return 0

def main():
    try:
        db = client(sdb_ip, sdb_port, sdb_user, sdb_password)
    except SDBBaseError as e:
        pysequoiadb._print(e)
        print("连接出错 请校验")
        sys.exit(0)
    cs = db.get_collection_space('face')
    try:
        ci = cs.get_collection(serverinfo_collection_name)
    except SDBBaseError as e:
        print("serverinfo表不存在，请建立")
        sys.exit(0)

    # 没有就创
    try:
        cl = cs.get_collection(collection_name)
    except SDBBaseError as e:
        cl = cs.create_collection(collection_name, {'ShardingKey': {"_id": 1},
                                                    'ShardingType': "hash",
                                                    'Partition': 65536,
                                                    'ReplSize': 1,
                                                    'Compressed': True,
                                                    'AutoSplit': True})
    records = []
    try:
        cr = ci.query()
        while True:
            try:
                import re
                ip_p = re.compile("\d+\.\d+\.\d+\.\d+")
                record = cr.next()
                if re.search(ip_p,record.get("ip")):
                    records.append(record)
            except SDBEndOfCursor:
                break
            except SDBBaseError as e:
                pysequoiadb._print(e)
    except SDBBaseError as e:
        pysequoiadb._print(e)
        sys.exit(0)
    finally:
        cr.close()

    # ip_ports=[[ip,port]...]
    ips = []
    ports = []
    for record in records:
        ips.append(record.get('ip'))
        ports.append(record.get('port'))
    ip_ports=zip(ips,ports)

    # cl.bulk_insert
    for ip_port in ip_ports:
        print(ip_port[0], '----', ip_port[1])
        ip_port_ = {'ip':ip_port[0],'port':ip_port[1]}
        ip_port_['ip_status'] = 1 if check_ping_status(ip_port[0]) else 0
        ip_port_['port_status'] = 1 if check_ip_port(ip_port[0],ip_port[1]) else 0
        timezone = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ip_port_['time'] = timezone

        # 有即更新，无即插入
        cl.upsert(rule={'$set':{'ip_status':ip_port_['ip_status'],
                                'port_status': ip_port_['port_status'],
                                'time':ip_port_['time']}},
                  condition={'ip':ip_port[0],'port':ip_port[1]})



if __name__ == "__main__":
    main()